<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use app\erp\model\ErpReturnandexchange;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 退换货管理
 * @package app\erp\model
 */
class Returnandexchangelogic{

    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function index($user_id, $order_id, $uid, $type, $return_status, $return_order_code){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' => $user_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($order_id != '')         $map[] = ['r.order_id', '=', $order_id];
            if($uid != '')              $map[] = ['r.uid', '=', $uid];
            if($type != '')             $map[] = ['r.type', '=', $type];
            if($return_status != '')    $map[] = ['r.return_status', '=', $return_status];
            if($return_order_code != '')$map[] = ['r.return_order_code', 'like','%'. $return_order_code.'%'];
			$list_data =  model('ErpReturnandexchange', 'model')->getList($map);//获取列表
            $list = $list_data['data'];
			$rel_list = [];
            foreach($list as $key => $value) {
                $rel_list[$key]['id'] = (int)$value['id'];
                $rel_list[$key]['orderId'] = (int)$value['order_id'];
                if ($value['type'] == '1') {
                    $typeNick = '退货';
                } elseif ($value['type'] == '2'){
                    $typeNick = '换货';
                }else{
                    $typeNick = '';
                }
				$rel_list[$key]['type'] 			= (int)$value['type'];
				$rel_list[$key]['typeNick'] 		= (string)$typeNick;
				$rel_list[$key]['reason'] 		    = (string)$value['reason'];
				$rel_list[$key]['content'] 	        = (string)$value['content'];
				$rel_list[$key]['imgUrl1']          = (string)$value['img_url1'];
				$rel_list[$key]['imgUrl2']          = (string)$value['img_url2'];
				$rel_list[$key]['imgUrl3']          = (string)$value['img_url3'];
                //$rel_list[$key]['uid'] 		        = (int)$value['uid'];
                $userInfo                           = controller('user_center/Userlogic', 'logic\user') -> get_user_info($value['uid'],$value['uid']);
                $rel_list[$key]['userInfo'] 		= $userInfo['data'];
                $rel_list[$key]['returnOrderCode']  = (string)$value['return_order_code'];
                if ($value['return_status'] == '1') {
                    $returnStatusNick = '已撤回';
                } elseif ($value['return_status'] == '2'){
                    $returnStatusNick = '已完成';
                }else{
                    $returnStatusNick = '申请中';
                }
                $rel_list[$key]['returnStatus'] 	= (int)$value['return_status'];
                $rel_list[$key]['returnStatusNick'] 	= (string)$returnStatusNick;
                $rel_list[$key]['createTime'] 		= (int)$value['create_time'];
                $rel_list[$key]['updateTime'] 		= (int)$value['update_time'];
                $rel_list[$key]['skuId'] 		    = (int)$value['sku_id'];
                $rel_list[$key]['num'] 		        = (int)$value['num'];
                $rel_list[$key]['price'] 		    = (float)$value['price'];
                $rel_list[$key]['totalprice'] 		= (float)($value['price']*$value['num']);
			}
            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加数据
     * @param order_id 	                int     订单id
     * @param type 		                int     类型 1退货 2换货
     * @param reason 		            string  退货理由
     * @param content 		            text    问题描述
     * @param img_url1 	                string  图片凭证1
     * @param img_url2 	                string  图片凭证2
     * @param img_url3 	                string  图片凭证3
     * @param create_time 		        int     创建时间
     * @param update_time 		        int     编辑时间
     * @param uid 		                int     添加人
     * @param return_order_code 		int     退换货订单号
     * @param return_status 		    int     订单状态 0申请中 1已撤回 2已完成
     * @param sku_id 		            int     规格id
     * @param num 		                int     数量
     * @param create_time 		        int     创建时间
     * @param update_time 		        int     编辑时间
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function add($user_id, $order_id, $type, $reason, $content, $img_url1, $img_url2, $img_url3, $return_order_code, $return_status,$sku_id,$num){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	        => $user_id,
				'order_id'          => $order_id,
                'type'              => $type,
                'reason' 	        => $reason,
                'content' 	        => $content,
                'img_url1'          => $img_url1,
                'img_url2'          => $img_url2,
                'img_url3'          => $img_url3,
                'return_order_code' => $return_order_code,
				'return_status' 	=> $return_status,
				'sku_id' 	        => $sku_id,
				'num' 	            => $num,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpReturnandexchange') -> addData($user_id, $order_id, $type, $reason, $content, $img_url1, $img_url2, $img_url3, $return_order_code, $return_status,$sku_id,$num);//添加
            if($rel['code'] == 200){
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success',$rel['data']);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 编辑
     * @param id 	                    int     申请单id
     * @param return_status 		    int     订单状态 0申请中 1已撤回 2已完成
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function editStatus($user_id,$id, $return_status){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	        => $user_id,
                'return_status' 	=> $return_status
            ];

            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpReturnandexchange') -> editStatus($user_id, $id, $return_status);
            if($rel['code'] == 200){
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }


    /**
     * 详情
     */
    public function detail($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' => $user_id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($id != '') $map[] = ['r.id', '=', $id];
            $list_data =  model('ErpReturnandexchange', 'model')->getList($map);//获取列表
            $list = $list_data['data'];
            $rel_list = [];
            foreach($list as $key => $value) {
                $rel_list[$key]['id'] = (int)$value['id'];
                $rel_list[$key]['orderId'] = (int)$value['order_id'];
                if ($value['type'] == '1') {
                    $typeNick = '退货';
                } elseif ($value['type'] == '2'){
                    $typeNick = '换货';
                }else{
                    $typeNick = '';
                }
                $rel_list[$key]['type'] 			= (int)$value['type'];
                $rel_list[$key]['typeNick'] 		= (string)$typeNick;
                $rel_list[$key]['reason'] 		    = (string)$value['reason'];
                $rel_list[$key]['content'] 	        = (string)$value['content'];
                $rel_list[$key]['imgUrl1']          = (string)$value['img_url1'];
                $rel_list[$key]['imgUrl2']          = (string)$value['img_url2'];
                $rel_list[$key]['imgUrl3']          = (string)$value['img_url3'];
                //$rel_list[$key]['uid'] 		        = (int)$value['uid'];
                $userInfo                           = controller('user_center/Userlogic', 'logic\user') -> get_user_info($value['uid'],$value['uid']);
                $rel_list[$key]['userInfo'] 		= $userInfo['data'];
                $rel_list[$key]['returnOrderCode']  = (string)$value['return_order_code'];
                if ($value['return_status'] == '1') {
                    $returnStatusNick = '已撤回';
                } elseif ($value['return_status'] == '2'){
                    $returnStatusNick = '已完成';
                }else{
                    $returnStatusNick = '申请中';
                }
                $rel_list[$key]['returnStatus'] 	= (int)$value['return_status'];
                $rel_list[$key]['returnStatusNick'] 	= (string)$returnStatusNick;
                $rel_list[$key]['createTime'] 		= (int)$value['create_time'];
                $rel_list[$key]['updateTime'] 		= (int)$value['update_time'];
                $rel_list[$key]['skuId'] 		    = (int)$value['sku_id'];
                $rel_list[$key]['num'] 		        = (int)$value['num'];
                $rel_list[$key]['price'] 		    = (float)$value['price'];
                $rel_list[$key]['totalprice'] 		= (float)($value['price']*$value['num']);
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/

        } catch (\Exception $e) {
            DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 删除
     * @param int $id
     * @author dou<51779987@qq.com>
     * @return bool
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpReturnandexchange') -> deleteData($id);
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }


    public function checkUpNum($user_id,$order_id, $sku_id)
    {
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	=> $user_id,
                'order_id' 	=> $order_id,
                'sku_id' 	=> $sku_id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            $map[] = ['order_id', '=', $order_id];
            $map[] = ['sku_id', '=', $sku_id];
            $rel = model('ErpGoodsOrderSkulist') ->where($map)->find();

            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success',$rel['num']);
            /********逻辑返回********/

        } catch (\Exception $e) {
            DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}